<template>
  <div class="app-container customer-div">
    <el-tabs v-model="activeName">
      <!-- 延迟基金 -->
      <el-tab-pane label="延迟基金" name="first">
        <el-form :inline="true" :model="listQuery1" size="mini" label-width="100px" style="margin-top: 40px">
          <el-form-item label="合同号：">
            <el-input v-model="listQuery1.orderSn" clearable></el-input>
          </el-form-item>
          <el-form-item label="排货单号：">
            <el-input v-model="listQuery1.billSn" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称：">
            <el-autocomplete
              clearable
              class="inline-input"
              value-key="customerName"
              :fetch-suggestions="querySearch"
              v-model="listQuery1.customerName"
              placeholder="请输入内容"
              @clear="clearKeywords"
              @select="handleSelectCustomerName"
              :trigger-on-focus="false"
              style="width: 270px;"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="业务员：">
            <el-select v-model="listQuery1.userId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采购员：">
            <el-select v-model="listQuery1.purchaseUserId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in purchaseOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="计息时间：">
            <el-date-picker
              v-model="listQuery1.computeTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="handleSearchList1()"
              type="primary">
              查询
            </el-button>
            <el-button
              :loading="btnLoading1"
              @click="downloadExcel1()"
              type="primary">
              导出
            </el-button>
          </el-form-item>
        </el-form>
        <div>
          <span style="margin-right: 10px;font-size:14px;">采购延迟金: <strong>{{ interestAmount.purchaseInterest }}</strong> </span>
          <span style="margin-right: 10px;font-size:14px;">物流延迟金: <strong>{{ interestAmount.deliverInterest }}</strong> </span>
          <span style="margin-right: 10px;font-size:14px;">总延迟金: <strong>{{ interestAmount.totalInterest }}</strong> </span>
        </div>
        <div class="table-container">
          <el-table
            v-loading="listLoading1"
            max-height="600"
            :data="tableData1"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column fixed="left" label="合同号" width="140" align="center" prop="orderSn">
            </el-table-column>
            <el-table-column fixed="left" label="客户名称" width="180" align="center" prop="customerName">
            </el-table-column>
            <el-table-column label="商品牌号" width="180" align="center" prop="goodsSn">
            </el-table-column>
            <el-table-column label="业务员" width="100" align="center" prop="userName">
            </el-table-column>
            <el-table-column label="采购员" width="100" align="center" prop="purchaseUserName">
            </el-table-column>
            <el-table-column label="合同金额" width="130" align="center" prop="orderAmount">
            </el-table-column>
            <el-table-column label="采购计息金额" width="130" align="center" prop="pComputeAmount">
            </el-table-column>
            <el-table-column label="采购延迟金" width="130" align="center" prop="pInterestAmount">
            </el-table-column>
            <el-table-column label="采购计息时间" width="130" align="center" prop="pComputeTime">
            </el-table-column>
            <el-table-column label="物流计息金额" width="130" align="center" prop="dComputeAmount">
            </el-table-column>
            <el-table-column label="物流延迟金" width="130" align="center" prop="dInterestAmount">
            </el-table-column>
            <el-table-column label="物流计息时间" width="130" align="center" prop="dComputeTime">
            </el-table-column>
            <el-table-column label="不执行计息金额" width="130" align="center" prop="unComputeAmount">
            </el-table-column>
            <el-table-column label="不执行延迟金" width="130" align="center" prop="unInterestAmoun">
            </el-table-column>
            <el-table-column label="不执行计息时间" width="130" align="center" prop="unComputeTime">
            </el-table-column>
            <el-table-column label="计息日期" width="130" align="center" prop="createdAt">
            </el-table-column>
            <el-table-column
              fixed="right"
              width="150"
              label="操作"
              align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="showFundCost(scope.row)">利息记录
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery1.pageNum"
            :page-size="listQuery1.pageSize"
            :page-sizes="[10,20,30,50]"
            :total="count1">
          </el-pagination>
        </div>
      </el-tab-pane>
      <!-- 利息记录 -->
      <el-tab-pane label="利息记录" name="second">
        <el-form :inline="true" :model="listQuery2" size="mini" label-width="100px" style="margin-top: 40px">
          <el-form-item label="合同号：">
            <el-input v-model="listQuery2.orderSn" clearable></el-input>
          </el-form-item>
          <el-form-item label="排货单号：">
            <el-input v-model="listQuery2.billSn" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称：">
            <el-autocomplete
              clearable
              class="inline-input"
              value-key="customerName"
              :fetch-suggestions="querySearch"
              v-model="listQuery2.customerName"
              placeholder="请输入内容"
              @clear="clearKeywords2"
              @select="handleSelectCustomerName2"
              :trigger-on-focus="false"
              style="width: 270px;"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="业务员：">
            <el-select v-model="listQuery2.userId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采购员：">
            <el-select v-model="listQuery2.purchaseUserId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in purchaseOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计息时间：">
            <el-date-picker
              v-model="listQuery2.computeTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="handleSearchList2()"
              type="primary">
              查询
            </el-button>
            <el-button
              :loading="btnLoading2"
              @click="downloadExcel2()"
              type="primary">
              导出
            </el-button>
          </el-form-item>
        </el-form>
        <div class="table-container">
          <el-table
            v-loading="listLoading2"
            max-height="600"
            :data="tableData2"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column fixed="left" label="合同号" min-width="140" align="center" prop="orderSn">
            </el-table-column>
            <el-table-column fixed="left" label="客户名称" min-width="200" align="center" prop="customerName">
            </el-table-column>
            <el-table-column label="商品牌号" min-width="200" align="center" prop="goodsSn">
            </el-table-column>
            <el-table-column label="业务员" min-width="100" align="center" prop="userName">
            </el-table-column>
            <el-table-column label="采购员" min-width="100" align="center" prop="purchaseUserName">
            </el-table-column>
            <el-table-column label="排货单号" min-width="160" align="center" prop="billSn">
            </el-table-column>
            <el-table-column label="合同金额" min-width="130" align="center" prop="orderAmount">
            </el-table-column>
            <el-table-column label="采购计息金额" min-width="130" align="center" prop="pComputeAmount">
            </el-table-column>
            <el-table-column label="采购延迟金" min-width="130" align="center" prop="pInterestAmount">
            </el-table-column>
            <el-table-column label="物流计息金额" min-width="130" align="center" prop="dComputeAmount">
            </el-table-column>
            <el-table-column label="物流延迟金" min-width="130" align="center" prop="dInterestAmount">
            </el-table-column>
            <el-table-column label="不执行计息金额" min-width="130" align="center" prop="unComputeAmount">
            </el-table-column>
            <el-table-column label="利率" min-width="130" align="center" prop="interestRate">
            </el-table-column>
            <el-table-column label="计息时间" min-width="130" align="center" prop="computeDate">
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery2.pageNum"
            :page-size="listQuery2.pageSize"
            :page-sizes="[10,20,30,50]"
            :total="count2">
          </el-pagination>
        </div>
      </el-tab-pane>
      <!-- 利率设置 -->
      <el-tab-pane label="利率设置" name="third">
        <el-form :inline="true" :model="listQuery2" size="mini" label-width="100px" style="margin-top: 40px">
          <el-form-item>
            <el-button
              @click="showForm()"
              type="primary">
              新增利率
            </el-button>
          </el-form-item>
        </el-form>
        <div class="table-container" style="width: 600px;">
          <el-table
            max-height="600"
            :data="tableData3"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column  label="利率" min-width="150" align="center">
              <template slot-scope="scope">
                {{scope.row.rateValue | fifnum}} %
              </template>
            </el-table-column>
            <el-table-column  label="设置日期" min-width="150" align="center" prop="createTime"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!--新增利率-->
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose"
      title="新增利率"
      :visible.sync="dialogVisible"
      width="400px">
      <el-form :model="quitForm" size="mini" label-width="120px" ref="quitForm" :rules="quitFormRules" >
        <el-form-item label="年利率：" prop="rateValue">
          <el-input type="number" v-model="quitForm.rateValue" clearable style="width:150px"></el-input><span> %</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseForm">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnFormLoading">确 定</el-button>
      </span>

    </el-dialog>

    <!-- 利息记录 -->
    <fundCostList ref="fundCostListRef"></fundCostList>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import fundCostList from './components/fundCostList.vue'
import {
  getFundOrderListAPI,
  getFundCostListAPI,
  getFundRateListAPI,
  getFundRateSetAPI,
} from '@/api/accounting';
import {
  getCustomerOption,
  getOrderUsersList
} from "@/api/partner";
const defaultListQuery1={
  orderSn: "", //合同编码
  billSn: "", //排货单号
  customerId: "", //客户ID
  customerName:'',
  userId: "", //业务员ID
  purchaseUserId: "", //采购员ID
  computeTime: [], //计息时间
  isExport: 0, //是否导出,0-否，1-是
  pageNum: 1, //第几页
  pageSize: 10 //每页几条
};

const defaultListQuery2 = {
  foId:'',//发货延迟基金ID
  orderSn: "", //合同编码
  billSn: "", //排货单号
  customerId: "", //客户ID
  customerName:'',
  userId: "", //业务员ID
  purchaseUserId: "", //采购员ID
  computeTime: [], //计息时间
  isExport: 0, //是否导出,0-否，1-是
  pageNum: 1, //第几页
  pageSize: 10 //每页几条
};

export default {
  name: "deliverDelayFundOrder",
  data() {
     const validateNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能小于0'))
      }
      callback()
    };
    return {
      activeName:'first',

      userOptionList: [],
      purchaseOptionList:[],
      listQuery1: JSON.parse(JSON.stringify(defaultListQuery1)),
      tableData1: [],
      count1: 0,
      listLoading1: false,
      btnLoading1: false,
      interestAmount:{},

      listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
      tableData2: [],
      count2: 0,
      listLoading2: false,
      dialogVisible2: false,
      btnLoading2: false,

      tableData3: [],

      dialogVisible: false,
      btnFormLoading:false,
      quitForm: {
        rateValue: ''
      },
      quitFormRules:{
        rateValue: [
          { required: true, trigger: 'blur', message: '请输入利率' },
          {validator:validateNum,trigger: "blur"}
        ],
      },
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  created() {
    this.getList1();
    this.getList2();
    this.getList3();
    this.getUserOptionList();
  },
  components:{
    fundCostList,
  },
  filters: {
    fifnum(val){
      if(val != ''){
        return parseFloat((val*100).toFixed(2))*1
      }else{
        return ''
      }
    }

  },
  methods: {
    showForm(){
      this.dialogVisible = true;
      this.quitForm.rateValue = '';
    },

    handleCloseForm(){
      this.dialogVisible = false;
      this.quitForm.rateValue = '';
      this.$refs.quitForm.resetFields();
    },

    handleConfirm() {
      this.$refs.quitForm.validate((valid) => {
        if (valid) {
          this.btnFormLoading = true;
          let data = JSON.parse(JSON.stringify(this.quitForm));
          data.rateValue = parseFloat((data.rateValue / 100).toFixed(4));
          getFundRateSetAPI(data).then(()=>{
            this.btnFormLoading = false;
            this.handleCloseForm();
            this.getList3();
          }).catch(()=>{
            this.btnFormLoading = false;
          })
        } else {
          return false;
        }
      });
    },

    getList3() {
      getFundRateListAPI().then(response => {
        this.tableData3 = response;
      }).catch(()=>{
      });
    },

    downloadExcel2(){
      let params = JSON.parse(JSON.stringify(this.listQuery2));
      params.isExport = 1;
      delete params.customerName;
      delete params.pageSize
      delete params.pageNum
      this.btnLoading2  = true;
      getFundCostListAPI(params).then((res)=>{
        this.btnLoading2 = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnLoading2 = false;
      })
    },
    getList2() {
      this.listLoading2 = true;
      let data = JSON.parse(JSON.stringify(this.listQuery2));
      delete data.customerName;
      getFundCostListAPI(data).then(response => {
        this.tableData2 = response.list;
        this.count2 = response.count;
        this.listLoading2 = false;
      }).catch(()=>{
        this.listLoading2 = false;
      });
    },
    handleSizeChange2(val){
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getList2();
    },
    handleCurrentChange2(val){
      this.listQuery2.pageNum = val;
      this.getList2();
    },
    handleSearchList2(){
      this.listQuery2.pageNum = 1;
      this.getList2();
    },
    clearKeywords2() {
      this.listQuery2.customerName = '';
      this.listQuery2.customerId = '';
    },
    handleSelectCustomerName2(item){
      this.listQuery2.customerName = item.customerName;
      this.listQuery2.customerId = item.customerId;
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
      getOrderUsersList({
        departmentType: "purchase"
      }).then((res)=>{
        this.purchaseOptionList = res;
      })
    },

    //选择客户名称
    handleSelectCustomerName(item){
      this.listQuery1.customerName = item.customerName;
      this.listQuery1.customerId = item.customerId;
    },
    //清除客户选择
    clearKeywords(){
      this.listQuery1.customerId = '';
      this.listQuery1.customerName = '';
    },
    //客户名称输入匹配
    querySearch(queryString, cb){
      getCustomerOption({keywords:queryString}).then((res)=>{
        cb(res);
      })
    },
    getList1() {
      this.listLoading1 = true;
      let data = JSON.parse(JSON.stringify(this.listQuery1));
      delete data.customerName;
      getFundOrderListAPI(data).then(response => {
        this.tableData1 = response.list;
        this.count1 = response.count;
        this.interestAmount = response.interestAmount;
        this.listLoading1 = false;
      }).catch(()=>{
        this.listLoading1 = false;
      });
    },
    handleSearchList1(){
      this.listQuery1.pageNum = 1;
      this.getList1();
    },
    handleSizeChange1(val){
      this.listQuery1.pageNum = 1;
      this.listQuery1.pageSize = val;
      this.getList1();
    },
    handleCurrentChange1(val){
      this.listQuery1.pageNum = val;
      this.getList1();
    },

    //显示利息记录弹窗
    showFundCost(item) {
      this.$refs.fundCostListRef.showPop(item);
    },
     //下载excle
    downloadExcel1(){
      let params = JSON.parse(JSON.stringify(this.listQuery1));
      params.isExport = 1;
      delete params.customerName;
      delete params.pageNum;
      delete params.pageSize;
      this.btnLoading1 = true;
      getFundOrderListAPI(params).then((res)=>{
        this.btnLoading1 = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnLoading1 = false;
      })
    },
      //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    toOrderDetail(orderId){
      let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:orderId,type:'see',seeType:'caiWu'}});
      window.open(routeData.href);
    },

    //关闭资金成本弹窗
    handleClose(){
      this.dialogVisible = false;
    },

  },
}
</script>

<style lang="scss">

</style>
